import os
import sys
# import xmltodict
from collections import defaultdict
from pprint import pprint

try:
    import xml.etree.CElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def traverse_xml(element):
    if len(element) > 0:
        for child in element:
            traverse_xml(child)
    else:
        content = element.text  # .strip()
        if not isinstance(content, type(None)):
            content = content.strip()
        print(element.tag, "--", content)


def xml2dict(xml_fn):
    try:
        tree = ET.parse(xml_fn)
        root = tree.getroot()
    except Exception as e:  # 捕获除与程序退出sys.exit()相关之外的所有异常
        print(e)
        print(f"parse {xml_fn} fail!")
        sys.exit()

    def recursiveXml(root):
        tdict = {}
        # 处理层级
        for subroot in list(root):
            if len(list(subroot)) > 0:
                retdict = recursiveXml(subroot)
                tdict.update({subroot.tag: retdict})
                continue
            content = subroot.text  # .strip()
            if not isinstance(content, type(None)):
                content = content.strip()
            tdict.update({subroot.tag: content})
        return tdict

    tdict = {}
    for subroot in list(root):
        # xmldict={root.tag:''}
        if len(list(subroot)) <= 0:
            content = subroot.text
            if not isinstance(content, type(None)):
                content = content.strip()
            tdict.update({subroot.tag: content})
        else:
            retdict = recursiveXml(subroot)
            tdict.update({subroot.tag: retdict})
    return {root.tag: tdict}
